#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QLabel>
#include <QStandardItemModel>
#include <QItemSelectionModel>
#include <QModelIndex>
#include <QFileDialog>
#include <QTextStream>
#include <QRegularExpression>

void MainWindow::initModelData(QStringList &stringList)
{
    int rowCount = stringList.size();
    if (rowCount < 1) return;

    m_model->setRowCount(rowCount - 1); // 第一行是标题

    QString header = stringList[0];
    // 用正则表达式将header切分开
    QStringList headerList = header.split(QRegularExpression(R"(\s+)"), Qt::SkipEmptyParts);
    m_model->setHorizontalHeaderLabels(headerList);

    for (int i = 1; i < rowCount; ++i) {
        int j;
        QStandardItem *item;

        QString lineText = stringList[i];
        QStringList tmpList = lineText.split(QRegularExpression(R"(\s+)"), Qt::SkipEmptyParts);
        assert(tmpList.size() <= kFixedColumnCount);

        // set 0..last-1 colunm. last is defined by column count of model
        for (j = 0; j < kFixedColumnCount - 1; ++j) {
            item = new QStandardItem(tmpList[j]);
            m_model->setItem(i - 1, j, item);
        }

        // last column
        item = new QStandardItem(tmpList[j]);
        item->setCheckable(true);
        item->setBackground(QBrush(Qt::yellow));
        if (tmpList[j] == "0") {
            item->setCheckState(Qt::Unchecked);
        }
        else {
            item->setCheckState(Qt::Checked);
        }
        m_model->setItem(i - 1, j, item);
    }
}

void MainWindow::do_currentChanged(const QModelIndex &current, const QModelIndex &previous)
{
    Q_UNUSED(previous);

    if (current.isValid()) {
        labCellPos->setText(QString::asprintf("当前单元格: %d行, %d列",
                                              current.row(), current.column()));
        QStandardItem *item = m_model->itemFromIndex(current);
        labCellText->setText("单元格内容: " + item->text());
        ui->actFontBold->setChecked(item->font().bold());
    }
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setCentralWidget(ui->splitter);

    labCurFile = new QLabel("当前文件", this);
    labCurFile->setMinimumWidth(200);
    labCellPos = new QLabel("当前单元格", this);
    labCellPos->setMinimumWidth(200);
    labCellText = new QLabel("当前单元格内容", this);
    labCellText->setMinimumWidth(200);

    ui->statusbar->addWidget(labCurFile);
    ui->statusbar->addWidget(labCellPos);
    ui->statusbar->addWidget(labCellText);

    m_model = new QStandardItemModel(2, kFixedColumnCount, this);
//    m_model->;

    m_selection = new QItemSelectionModel(m_model, this);

    ui->tableView->setModel(m_model);
    ui->tableView->setSelectionModel(m_selection);
    ui->tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectItems);

    connect(m_selection, &QItemSelectionModel::currentChanged, this, &MainWindow::do_currentChanged);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_actOpenFile_triggered()
{
    // 获取当前应用程序路径
    QString curPath = QCoreApplication::applicationDirPath();
    QString fileName = QFileDialog::getOpenFileName(this, "打开一个文件", curPath, "数据文件(*.txt);;所有文件(*.*)");
    if (fileName.isEmpty())
        return;

    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { // fail
        return;
    }

    QStringList fileContent;
    ui->plainTextEdit->clear();
    QTextStream stream(&file); // 流方式读文件

    // 将文件内容逐行读取到字符串列表
    while (!stream.atEnd()) {
        QString str = stream.readLine();
        ui->plainTextEdit->appendPlainText(str);
        fileContent.append(str);
    }
    file.close();

    labCurFile->setText("当前文件: " + fileName);
    ui->actAppendRow->setEnabled(true);
    ui->actInsertRow->setEnabled(true);
    // TODO: Add action save
//    ui->actSave->setEnabled(true);
    ui->actDeleteRow->setEnabled(true);

    // 根据模型数据(字符串列表), 初始化table view数据
    initModelData(fileContent);
}


void MainWindow::on_actScanData_triggered()
{
    ui->plainTextEdit->clear();
    QStandardItem *item;
    QString str;

    // 表头
    for (int i = 0; i < m_model->columnCount(); ++i) {
        item = m_model->horizontalHeaderItem(i);
        str += item->text();
        str += "\t";
    }
    ui->plainTextEdit->appendPlainText(str);

    // 表内容
    for (int i = 0; i < m_model->rowCount(); ++i) {
        int j;
        str.clear();
        // 0~倒数第二列
        for (j = 0; j < m_model->columnCount() - 1; ++j) {
            item = m_model->item(i, j);
            str += item->text();
            str += "\t";
        }
        // 最后一列, 含复选框, 特殊处理
        item = m_model->item(i, j);
        if (item->checkState() == Qt::Checked)
            str += "是";
        else
            str += "否";

        ui->plainTextEdit->appendPlainText(str);
    }
}


void MainWindow::on_actAppendRow_triggered()
{
    QList<QStandardItem *> itemList;
    QStandardItem *item;

    for (int i = 0; i < m_model->columnCount() - 1; ++i) {
        item = new QStandardItem("0");
        itemList << item;
    }
    QString str;
    str = (m_model->rowCount() % 2) ? "0" : "1";
    item = new QStandardItem(str);
    item->setCheckable(true);
    item->setCheckState(str == "1" ? Qt::Checked : Qt::Unchecked);
    item->setBackground(QBrush(Qt::yellow));
    itemList << item;

    m_model->insertRow(m_model->rowCount(), itemList);
    m_selection->clearSelection();
    m_selection->setCurrentIndex(m_model->index(m_model->rowCount() - 1, 0),
                                 QItemSelectionModel::Select);
}


void MainWindow::on_actInsertRow_triggered()
{
    QList<QStandardItem *> itemList;
    QStandardItem *item;

    for (int i = 0; i < m_model->columnCount() - 1; ++i) {
        item = new QStandardItem("0");
        itemList << item;
    }
    QString str;
    str = (m_model->rowCount() % 2) ? "0" : "1";
    item = new QStandardItem(str);
    item->setCheckable(true);
    item->setCheckState(str == "1" ? Qt::Checked : Qt::Unchecked);
    item->setBackground(QBrush(Qt::yellow));
    itemList << item;

    QModelIndex curIndex = m_selection->currentIndex();
    m_model->insertRow(curIndex.row(), itemList);
    m_selection->clearSelection();
    m_selection->setCurrentIndex(curIndex, QItemSelectionModel::Select);
}


void MainWindow::on_actDeleteRow_triggered()
{
    QModelIndex curIndex = m_selection->currentIndex();
    if (curIndex.row() != m_model->rowCount() - 1) {
        m_model->removeRow(curIndex.row());
        m_selection->setCurrentIndex(curIndex, QItemSelectionModel::Select);
    }
    else {
        m_model->removeRow(curIndex.row());
    }
}


void MainWindow::on_actAlignLeft_triggered()
{
    if (!m_selection->hasSelection())
        return;

    // 多选
    QModelIndexList indexList = m_selection->selectedIndexes();
    for (auto &index : indexList) {
        m_model->itemFromIndex(index)->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    }
}


void MainWindow::on_actAlignCenter_triggered()
{
    if (!m_selection->hasSelection())
        return;

    // 多选
    QModelIndexList indexList = m_selection->selectedIndexes();
    for (auto &index : indexList) {
        m_model->itemFromIndex(index)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    }
}


void MainWindow::on_actAlignRight_triggered()
{
    if (!m_selection->hasSelection())
        return;

    // 多选
    QModelIndexList indexList = m_selection->selectedIndexes();
    for (auto &index : indexList) {
        m_model->itemFromIndex(index)->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
    }
}


void MainWindow::on_actFontBold_triggered(bool checked)
{
    if (!m_selection->hasSelection())
        return;

    QModelIndexList indexList = m_selection->selectedIndexes();
    for (auto &index : indexList) {
        QFont font = m_model->itemFromIndex(index)->font();
        font.setBold(checked);
        m_model->itemFromIndex(index)->setFont(font);
    }
}

